package com.zut.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zut.pojo.AddressBook;
import com.zut.pojo.R;
import com.zut.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;


    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook, HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        log.info("添加的信息：{}",addressBook);
        addressBookService.save(addressBook);

        return R.success("添加收货地址成功");
    }


    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook,HttpSession session){

        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);

        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(addressBook.getUserId() != null,AddressBook::getUserId,addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(queryWrapper);


        return R.success(list);
    }


    @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook,HttpSession session){
        LambdaUpdateWrapper<AddressBook> updateWrapper = new LambdaUpdateWrapper<>();
        Long userId = (Long) session.getAttribute("user");
        updateWrapper.eq(AddressBook::getUserId,userId);
        updateWrapper.set(AddressBook::getIsDefault,0);
        addressBookService.update(updateWrapper);

        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);

        return R.success("设为默认地址成功");
    }


    @GetMapping("/{id}")
    public R<AddressBook> selectById(@PathVariable Long id){

        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getId,id);
        AddressBook one = addressBookService.getOne(queryWrapper);

        return R.success(one);
    }


    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){

        addressBookService.updateById(addressBook);

        return R.success("修改成功");
    }


    @DeleteMapping
    public R<String> deleteById(@RequestParam Long ids){
        addressBookService.removeById(ids);

        return R.success("删除成功");
    }

}
